<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { getDepartmentList } from '@T2/utils/users.ts';
import { api } from '@T2/plugins/env-config.ts';
import { caeventv1stepApi as MainApi, eventv1ById, iuserApi } from '@T2/service/api.ts';
import { findNodeByProperty } from '@T2/utils/utils.ts';
import { useCurrentWatchStore, useIuserInfoStore } from '@T2/store/users.ts';
import ImagePreview from '@T2/components/imagePreview/index.vue';
import UploadImage from '@T2/components/uploadImage/index.vue';
import UploadAttachment from '@T2/components/uploadAttachment/index.vue';
import Detail from './components/detail.vue';
import StepDetail from './components/stepDetail.vue';

const iuserInfoStore = useIuserInfoStore();
const { info } = iuserInfoStore;
const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

const { type, content } = defineProps({
  type: {
    type: String,
    validator(value) {
      return ['详情', '派单', '接单', '处理', '验收'].includes(value);
    },
    required: true,
  },
  content: {
    type: Object,
    required: true,
  },
});
const emits = defineEmits(['close']);
const visible = ref(true);

const Resd = reactive({
  list: [],
  departmentList: [],
});
onMounted(async () => {
  GetMainTable();
  if (content.status === '待派单' && type === '派单') {
    initPaidanFormModel();
  } else if (content.status === '待处理' && type === '处理') {
    initChuliFormModel();
  } else if (content.status === '待验收' && type === '验收') {
    initYanshouFormModel();
  }
  Resd.departmentList = await getDepartmentList();
});
const GetMainTable = () => {
  MainApi({
    method: 'get',
    params: {
      eventv1: content.id,
    }
  }).then(res => {
    Resd.list = res?.results || [];
  });
}

const stepLoading = ref(false);
/* 工单派单 */
const paidanForm = reactive({
  model: {},
  fj_json: [],
  fj_updateTimes: 0,
});
const paidanFormRef = ref(null);
const paidanProps = {
  value: 'id',
  emitPath: false,
  label: 'name',
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    if (level === 0) {
      const arr = Resd.departmentList.map(i => {
        return { id: i.id, name: i.name };
      });
      resolve(arr);
    } else {
      const arr = getDepartmentNextLevel(node.data.id);
      iuserApi({
        method: 'get',
        params: {
          department: node.data.id
        }
      }).then(res => {
        const userArrs = (res?.results || []).map(i => {
          return { id: i.id, name: i.truename, leaf: true }
        });
        if (!userArrs.length) {
          userArrs.push({ id: null, name: '无', disabled: true, leaf: true });
        }
        resolve(arr.concat(userArrs));
      })
    }
  },
}
const getDepartmentNextLevel = (departmentID = null) => {
  const department = findNodeByProperty(Resd.departmentList, 'id', departmentID);
  const arr = department?.children.map(i => {
    return { id: i.id, name: i.name }
  }) || [];
  return arr;
}
const initPaidanFormModel = () => {
  paidanForm.model = {
    spuser: null,
    clsq: '',
    wx: false,
    info: '',
    fj: [],
  };
  paidanForm.fj_json = [];
  paidanForm.fj_updateTimes++;
  nextTick(() => {
    paidanFormRef.value.clearValidate();
  });
}
const paidanFjChange = (files) => {
  paidanForm.model.fj = files;
}
const addPaidanstep = () => {
  if (!paidanForm.model.info) {
    ElMessage.error('请输入处理方案！');
    stepLoading.value = false;
    return false;
  }
  MainApi({
    method: 'post',
    data: {
      ...paidanForm.model,
      action: '工单派单',
      project: curProject.id,
      eventv1: content.id,
      creater: info.id,
    }
  }).then(res => {
    changeEventv1Status('派单成功', '待接单');
  }).catch(err => {
    stepLoading.value = false;
  })
}
/* 工单接单 */
const addJiedanStep = () => {
  MainApi({
    method: 'post',
    data: {
      action: '工单接单',
      project: curProject.id,
      eventv1: content.id,
      creater: info.id,
    }
  }).then(res => {
    changeEventv1Status('接单成功', '待处理');
  }).catch(err => {
    stepLoading.value = false;
  })
}
/* 工单处理 */
const chuliForm = reactive({
  model: {},
  files_json: [],
  files_updateTimes: 0,
  fj_json: [],
  fj_updateTimes: 0,
});
const chuliFormRef = ref(null);
const initChuliFormModel = () => {
  chuliForm.model = {
    cyusers: '',
    llqd: '',
    info: '',
    files: [],
    fj: [],
  };
  chuliForm.files_json = [];
  chuliForm.files_updateTimes++;
  chuliForm.fj_json = [];
  chuliForm.fj_updateTimes++;
  nextTick(() => {
    chuliFormRef.value.clearValidate();
  });
}
const chuliFilesChange = (files) => {
  chuliForm.model.files = files;
}
const chuliFjChange = (files) => {
  chuliForm.model.fj = files;
}
const addChuliStep = () => {
  if (!chuliForm.model.info) {
    ElMessage.error('请输入处理说明！');
    stepLoading.value = false;
    return false;
  }
  MainApi({
    method: 'post',
    data: {
      ...chuliForm.model,
      action: '工单处理',
      project: curProject.id,
      eventv1: content.id,
      creater: info.id,
    }
  }).then(res => {
    changeEventv1Status('处理成功', '待验收');
  }).catch(err => {
    stepLoading.value = false;
  })
}
/* 工单验收 */
const yanshouForm = reactive({
  model: {},
  files_json: [],
  files_updateTimes: 0,
});
const yanshouFormRef = ref(null);
const initYanshouFormModel = () => {
  yanshouForm.model = {
    complete: false,
    info: '',
    files: [],
  };
  yanshouForm.files_json = [];
  yanshouForm.files_updateTimes++;
  nextTick(() => {
    yanshouFormRef.value.clearValidate();
  });
}
const yanshouFilesChange = (files) => {
  yanshouForm.model.files = files;
}
const addYanshouStep = () => {
  if (!yanshouForm.model.info) {
    ElMessage.error('请输入验收内容！');
    stepLoading.value = false;
    return false;
  }
  MainApi({
    method: 'post',
    data: {
      ...yanshouForm.model,
      action: '工单验收',
      project: curProject.id,
      eventv1: content.id,
      creater: info.id,
    }
  }).then(res => {
    changeEventv1Status('验收成功', '已完成');
  }).catch(err => {
    stepLoading.value = false;
  })
}
const changeEventv1Status = (message, status) => {
  eventv1ById({
    method: 'patch',
    id: content.id,
    data: {
      status,
    }
  }).then(res => {
    emits('close', true);
    ElMessage.success(message);
    stepLoading.value = false;
  }).catch(err => {
    stepLoading.value = false;
  });
}



const closeClick = () => {
  emits('close', false);
}
const submitClick = () => {
  stepLoading.value = true;
  if (type === '派单') {
    addPaidanstep();
  } else if (type === '接单') {
    addJiedanStep();
  } else if (type === '处理') {
    addChuliStep();
  } else if (type === '验收') {
    addYanshouStep();
  }
}

/* 图片查看 */
const imgPopup = reactive({
  visible: false,
  images: [],
});
const showImages = (arrs) => {
  imgPopup.visible = true;
  imgPopup.images = [];
  arrs?.forEach(item => {
    imgPopup.images.push({
      id: item.id,
      name: item.name,
      url: `${ api + item.file_url }`,
    });
  });
}
</script>

<template>
  <div>
    <el-drawer v-model="visible" size="980" @close="closeClick()">
      <template #header>
        <div class="head-name">工单{{ type }}</div>
      </template>
      <template #default>
        <div class="content-box">
          <el-steps direction="vertical" :active="3">
            <!-- 工单信息-->
            <Detail :content="content" @showImages="showImages" />
            
            <!-- 工单步骤-->
            <StepDetail :content="content" @showImages="showImages" />
            
            <!-- 工单派单-->
            <el-step v-if="content.status === '待派单' && type === '派单'">
              <template #icon>
                <div class="step-icon"></div>
              </template>
              <template #title>
                <div class="title-line1 flex--center">
                  <span class="title-name">工单派单</span>
                </div>
              </template>
              <template #description>
                <div class="step-box">
                  <el-form
                    ref="paidanFormRef"
                    :model="paidanForm.model"
                    label-width="100px"
                    class="flex flex-wrap"
                  >
                    <el-form-item style="width: 50%;" prop="spuser" label="处理人员：">
                      <el-cascader v-model="paidanForm.model.spuser" :props="paidanProps" v-if="Resd.departmentList.length"/>
                    </el-form-item>
                    <el-form-item style="width: 50%;" prop="clsq" label="材料申请：">
                      <el-input style="width: 100%;" v-model="paidanForm.model.clsq" />
                    </el-form-item>
                    <el-form-item style="width: 50%;" prop="wx" label="是否外协：">
                      <el-radio-group v-model="paidanForm.model.wx">
                        <el-radio :value="true">是</el-radio>
                        <el-radio :value="false">否</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item style="width: 100%;" prop="info" label="处理方案：">
                      <el-input
                        style="width: 100%;"
                        v-model="paidanForm.model.info"
                        placeholder="请输入内容"
                        type="textarea"
                        :rows="5"
                      />
                    </el-form-item>
                    <el-form-item style="width: 50%;" prop="fj" label="上传附件：">
                      <UploadAttachment
                        :fj_json="paidanForm.fj_json"
                        :updateTimes="paidanForm.fj_updateTimes"
                        :maxSizeMB="20"
                        @files-change="paidanFjChange"
                      >
                        <div class="upload_info" style="margin-top: 6px">请上传必要的说明文件，不超过20MB</div>
                      </UploadAttachment>
                    </el-form-item>
                  </el-form>
                </div>
              </template>
            </el-step>
            
            <!-- 工单处理-->
            <el-step v-if="content.status === '待处理' && type === '处理'">
              <template #icon>
                <div class="step-icon"></div>
              </template>
              <template #title>
                <div class="title-line1 flex--center">
                  <span class="title-name">工单处理</span>
                </div>
              </template>
              <template #description>
                <div class="step-box">
                  <el-form
                    ref="chuliFormRef"
                    :model="chuliForm.model"
                    label-width="100px"
                    class="flex flex-wrap"
                  >
                    <el-form-item style="width: 50%;" prop="cyusers" label="参与人员：">
                      <el-input style="width: 100%;" v-model="chuliForm.model.cyusers" />
                    </el-form-item>
                    <el-form-item style="width: 50%;" prop="llqd" label="领料清单：">
                      <el-input style="width: 100%;" v-model="chuliForm.model.llqd" />
                    </el-form-item>
                    <el-form-item style="width: 100%;" prop="info" label="处理说明：">
                      <el-input
                        style="width: 100%;"
                        v-model="chuliForm.model.info"
                        placeholder="请输入内容"
                        type="textarea"
                        :rows="5"
                      />
                    </el-form-item>
                    <el-form-item style="width: 100%;" prop="files" label="上传图片：">
                      <UploadImage
                        :files_json="chuliForm.files_json"
                        :updateTimes="chuliForm.files_updateTimes"
                        :maxSizeMB="5"
                        @files-change="chuliFilesChange"
                      />
                      <div class="upload_info">请上传JPG/PNG/格式文件，不超过5MB</div>
                    </el-form-item>
                    <el-form-item style="width: 50%;" prop="fj" label="上传附件：">
                      <UploadAttachment
                        :fj_json="chuliForm.fj_json"
                        :updateTimes="chuliForm.fj_updateTimes"
                        :maxSizeMB="20"
                        @files-change="chuliFjChange"
                      >
                        <div class="upload_info" style="margin-top: 6px">请上传必要的说明文件，不超过20MB</div>
                      </UploadAttachment>
                    </el-form-item>
                  </el-form>
                </div>
              </template>
            </el-step>
            
            <!-- 工单验收-->
            <el-step v-if="content.status === '待验收' && type === '验收'">
              <template #icon>
                <div class="step-icon"></div>
              </template>
              <template #title>
                <div class="title-line1 flex--center">
                  <span class="title-name">工单验收</span>
                </div>
              </template>
              <template #description>
                <div class="step-box">
                  <el-form
                    ref="yanshouFormRef"
                    :model="yanshouForm.model"
                    label-width="100px"
                    class="flex flex-wrap"
                  >
                    <el-form-item style="width: 50%;" prop="complete" label="是否完成：">
                      <el-radio-group v-model="yanshouForm.model.complete">
                        <el-radio :value="true">是</el-radio>
                        <el-radio :value="false">否</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item style="width: 100%;" prop="info" label="验收内容：">
                      <el-input
                        style="width: 100%;"
                        v-model="yanshouForm.model.info"
                        placeholder="请输入内容"
                        type="textarea"
                        :rows="5"
                      />
                    </el-form-item>
                    <el-form-item style="width: 100%;" prop="files" label="上传图片：">
                      <UploadImage
                        :files_json="yanshouForm.files_json"
                        :updateTimes="yanshouForm.files_updateTimes"
                        :maxSizeMB="5"
                        @files-change="yanshouFilesChange"
                      />
                      <div class="upload_info">请上传JPG/PNG/格式文件，不超过5MB</div>
                    </el-form-item>
                  </el-form>
                </div>
              </template>
            </el-step>
          </el-steps>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <template v-if="content.status === '待派单' && type === '派单'">
            <el-button @click="closeClick()">取 消</el-button>
            <el-button type="primary" @click="submitClick()" :disabled="stepLoading">提 交</el-button>
          </template>
          <template v-else-if="content.status === '待接单' && type === '接单'">
            <el-button @click="closeClick()">取 消</el-button>
            <el-button type="primary" @click="submitClick()" :disabled="stepLoading">确认接单</el-button>
          </template>
          <template v-else-if="content.status === '待处理' && type === '处理'">
            <el-button @click="closeClick()">取 消</el-button>
            <el-button type="primary" @click="submitClick()" :disabled="stepLoading">提 交</el-button>
          </template>
          <template v-else-if="content.status === '待验收' && type === '验收'">
            <el-button @click="closeClick()">取 消</el-button>
            <el-button type="primary" @click="submitClick()" :disabled="stepLoading">提 交</el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="closeClick()">关 闭</el-button>
          </template>
        </div>
      </template>
    </el-drawer>
    
    <el-dialog v-model="imgPopup.visible" title="图片预览" width="fit-content">
      <div style="width: 800px; height: 600px;">
        <ImagePreview :images="imgPopup.images"/>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.step-icon {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #0079FE;
}
.step-box {
  margin-top: 4px;
}
.content-box {
  
}
</style>

<style scoped>
:deep(.el-drawer__body) {
  padding: 26px 0 26px 38px;
}
:deep(.el-drawer__header) {
  height: 60px;
  padding-bottom: 10px;
  margin-bottom: 0;
  border-bottom: 1px solid #EDEFF3;
}
:deep(.el-drawer__header .head-name) {
  font-weight: 500;
  font-size: 20px;
  color: #252525;
}
:deep(.el-step__title) {
  display: flex;
  align-items: center;
}
:deep(.el-step__description) {
  padding-right: 38px !important;
  padding-bottom: 32px;
}

</style>